unit FileServerThreadU;

interface
uses
  FileCtrl, Classes, SysUtils,  kbmMemTable, IdTCPServer, FileServerProtocol;

type
  TFileServerThread = class(TIdPeerThread)
  protected
    fLocalFilename:String;
    procedure BeforeExecute; override;
    procedure AfterExecute; override;
  public
    FileName, SavePath:String;
    FileType: TTransFileType;
    FileSize: Cardinal;
    FileStream: TFileStream;
    ErrorMessage:String;
    Function OpenStream: Boolean;
    Procedure CloseStream;
    property LocalFileName:string read fLocalFilename;
  end;


implementation

{ TSQLThread }

procedure TFileServerThread.AfterExecute;
begin
  inherited;
  CloseStream;
end;

procedure TFileServerThread.BeforeExecute;
begin
  inherited;
  FileStream := nil;
end;

procedure TFileServerThread.CloseStream;
begin
  if Assigned(FileStream) then
  begin
    FileStream.Free;
    FileStream := nil;
  end;
end;

Function TFileServerThread.OpenStream: Boolean;
begin
  Result := False;
  fLocalFileName := SavePath;

  if Trim(fLocalFilename) = EmptyStr then
  begin
    ErrorMessage := 'File Save Path was not received.';
    exit;
  end;

  if fLocalFilename[Length(fLocalFilename)] = '\' then fLocalFilename := Copy(fLocalFilename,1, Length(fLocalFilename));
  if not DirectoryExists (fLocalFilename) then
  begin
    if not ForceDirectories(fLocalFilename) then
    begin
      ErrorMessage := format('Mkdir (%s) Fail',[fLocalFilename]);
      exit;
    end;
  end;
  fLocalFilename := fLocalFilename + '\' + Filename;

  try
    if FileExists(fLocalFilename) then
    DeleteFile(fLocalFilename);

    FileStream := TFileStream.Create(fLocalFilename, fmCreate);
  except on e: Exception do
    begin
      ErrorMessage := format('[%s]%s',[fLocalFilename, e.message]);
      exit;
    end;
  end;
  Result := True;
end;

end.
